define(function (require, exports, module) {
    var angular = require('angular');
    var util = require('util');
    var $ = require('jquery');
    require("angular-ui");
    require("authorize");
    require("permission");
    require("angular-interceptor");
    require("pagination");
    require('./data_init/projTree');
    require('./data_init/joinTeam');
    require('/static_public/js/angular_directive/projectTreeSelector');

    angular.module('app', ['ngInterceptor', 'ngUI', 'ProjTreeSelector','projectTreeSelector', 'teamAdd'])
        .constant('api.path', {
            datainit: "/api/index.php?r=datainit/",
            initproject: "/api/index.php?r=init/",
            saleruser: "/api/index.php?r=salesuser/"
        })
        .factory('DataInitService', [
            '$http',
            'api.path',
            function ($http, api_path) {
                var httpClient = {
                    get: function (api, data, proj) {
                        var url = api_path[proj] + api;
                        var search = (data && data.search) || {};
                        angular.forEach(search, function (val, key) {
                            url += "&" + key + "=" + val;
                        });

                        return $http.get(url)
                            .then(function (res) {
                                res = res.data;
                                if (res.retCode == "0") {
                                    return res;
                                }
                            })
                    },
                    post: function (api, data, proj) {
                        var url = api_path[proj] + api;
                        var search = (data && data.search) || {};
                        angular.forEach(search, function (val, key) {
                            url += "&" + key + "=" + val;
                        });

                        return $http.post(url, (data && data.data) || {})
                            .then(function (res) {
                                res = res.data;
                                if (res.retCode == "0") {
                                    return res;
                                }
                            })
                    },
                    download: function(api, data, proj) {
                        var url = api_path[proj] + api;
                        var search = (data && data.search) || {};
                        angular.forEach(search, function (val, key) {
                            url += "&" + key + "=" + val;
                        });
                        return url;
                    }
                }
                return {
                    getUserInitData: function(search){
                        return httpClient.get('data-init/check-enable-do-init', search, "initproject")
                    },
                    getProjectList: function (search) {
                        return httpClient.get('data-init/get-init-data-project-list', search, "initproject")
                    },
                    initData: function (data) {
                        return httpClient.post('add-user', data, "datainit")
                    },
                    checkProject: function(search) {
                        return httpClient.get('data-init/check-project', search, "initproject")
                    },
                    checkSite: function(search){
                        return httpClient.get('data-init/check-erp-site-connect', search, "initproject")
                    },
                    saveInitRules: function(data){
                        return httpClient.post('data-init/save-project-init-rule', data, "initproject")
                    },
                    getInitRecordCount: function(search){
                        return httpClient.get('data-init/get-all-records-count', search, "initproject")
                    },
                    getStepStatus: function(search){
                        return httpClient.get('data-init/get-first-step-info-list', search, "initproject")
                    },
                    getInitStatus: function(search){
                        return httpClient.get('data-init/get-second-step-info-list', search, "initproject")
                    },
                    getSalerProjectList: function (data) {
                        return httpClient.post('project/get-list-by-ids', data, "saleruser")
                    },
                    markDeparture: function (data) {
                        return httpClient.post('sales-user/disable', data, "saleruser")
                    },
                    markOnDuty: function (data) {
                        return httpClient.post('sales-user/enable', data, "saleruser")
                    },
                    getSalerList: function (search) {
                        return httpClient.get('data-init/get-init-sale-list', search, "initproject")
                    },
                    addTeamUsers: function (data) {
                        return httpClient.post('data-init/batch-join', data, "initproject")
                    },
                    getUnbindErpUsers: function(search){
                        return httpClient.get('data-init/get-unbind-erp-user-list', search, "initproject")
                    },
                    exportUnbindErpUsers: function(search){
                        return httpClient.download('data-init/export-unbind-erp-user-list', search, "initproject")
                    },
                    getTeamInfo: function(search){
                        return httpClient.get('sales-team/list', search, "saleruser")
                    },
                    updateSaler: function(data){
                        return httpClient.post('sales-user/save', data, "saleruser")
                    },
                    getSyncErpList: function(search){
                        return httpClient.get('sync-params/get-sync-erp-params-list', search, "initproject")
                    },
                    syncErpParam: function(data){
                        return httpClient.post('sync-params/exec-sync-erp-params', data, "initproject")
                    },
                    syncErpParams: function(data){
                        return httpClient.post('sync-params/exec-sync-erp-params-all', data, "initproject")
                    },
                    updateErpParam: function(data){
                        return httpClient.post('sync-params/save-sync-erp-params', data, "initproject")
                    },  
                    importSyncErpList: function(search){
                        return httpClient.get('sync-params/import-sync-erp-params', search, "initproject")
                    },
                    syncErp: function(data){
                        return httpClient.post('sales-team/edit-saler', data, "saleruser")
                    }
                }
            }
        ])
        .controller('DataInitController', [
            '$scope',
            '$rootScope',
            '$timeout',
            '$interval',
            '$window',
            'DataInitService',
            function ($scope, $rootScope, $timeout,$interval, $window,service) {

                $scope.getProjectList = function () {
               
                    $scope.curStep = "selectProj";
                    service.getProjectList()
                        .then(function (res) {
                            $scope.projs = res.data;
                        })
                       
                };

                /** 
                 * 监听项目树选择
                 */
                $scope.$watch('selectProjects', function (val) {
                    if (val) {
                        var selectProjects = JSON.parse(val);

                        var selectedProjList = [];

                        angular.forEach(selectProjects, function (proj, id) {
                            selectedProjList.push(proj);
                        });

                        $scope.selectedProjList = selectedProjList;
                    }
                });

                /** 
                 * 删除所选项目
                 */
                $scope.deselectProj = function (index) {
                    var selected = $scope.selectedProjList[index];

                    $scope.selectedProjList.splice(index, 1);

                    var obj = {};

                    angular.forEach($scope.selectedProjList, function (proj) {
                        obj[proj.id] = proj;
                    });

                    $scope.selectProjects = JSON.stringify(obj);

                    $scope.$broadcast('delProj', selected);
                };
                
                $scope.deselectAllProj = function(){
                    angular.forEach($scope.selectedProjList, function (proj) {
                        $scope.$broadcast('delProj', proj);
                    });
                    $scope.selectedProjList = [];
                    $scope.selectProjects = "";
                    
                };
                /** 
                 * 初始化项目
                 */
                $scope.initPorj = function () {
                    if (!$scope.selectedProjList || !$scope.selectedProjList.length) {
                        return;
                    }
                    
                    $scope.showInitCheck();
                    
                    $scope.recheck();
                    
                };
                
                $scope.checkSite = function(){
                    service.checkSite({
                        search: {}
                    })  
                        .then(function(res){
                            $scope.isSiteOk = res.data;
                        })
                };
                /** 
                 * 取消初始化检查
                 */
                $scope.cancelInitCheck = function() {
                    $scope.curStep = "selectProj";    
                    $scope.deselectAllProj();
                };
                /** 
                 * 显示初始化检查界面
                 */
                $scope.showInitCheck = function() {
                    $scope.curStep = "initProj";
                };
                /** 
                 * 取消初始化项目
                 */
                $scope.cancelInit = function(index){
                    if (index === undefined || $scope.selectedProjList.length === 1) {
                        $scope.cancelInitCheck();
                    } else {
                        $scope.deselectProj(index);
                    }
                    $scope.checkCompleted();
                };
                $scope.apps = {
                    "5001": "微楼书(旧版)",
                    "7001": "微支付商城",
                    "5020": "秒杀活动",
                    "5008": "小蜜蜂",
                    "5005": "分享达人",
                    "5009": "微楼书(新版)",
                    "5021": "认筹理财",
                    "5002": "移动销售",
                    "5003": "全民营销",
                    "6001": "云服务",
                    "5030": "旺财宝"
                }
                /** 
                 * 重新检查
                 */
                $scope.recheck = function(index){
                    angular.forEach($scope.selectedProjList,function(proj){
                        proj.isCompleted = false;
                        try {
                            proj.authYDXS = proj.authorize.applicationCode.join(',').indexOf('5002') > -1;
                        } catch(e){
                            
                        }
                        service.checkProject({
                            search: {
                                projectId: proj.id
                            }
                        })
                            .then(function(res){
                                proj.isCompleted = true;
                                var data = res.data;
                                var authProjs = [],unAuthProjs = [];
                                angular.forEach(data.authorizeUseStatus.used,function(code){
                                    authProjs.push($scope.apps[code]);
                                });
                                angular.forEach(data.authorizeUseStatus.unused,function(code){
                                    unAuthProjs.push($scope.apps[code]);
                                });
                                angular.extend(proj,data,{
                                    authProjs: authProjs.join('、'),
                                    unAuthProjs: unAuthProjs.join('、'),
                                });
                                
                                $scope.checkCompleted();
                            })
                        
                    });
                    
                    $scope.checkSite();
                };
                
                $scope.checkCompleted = function(){
                    var isCompleted = true;
                    var unAuthYDXS = true;
                    for(var i = 0; i < $scope.selectedProjList.length;i++) {
                        var proj = $scope.selectedProjList[i];
                        //第一条默认展开
                        if (i === 0) {
                            proj.selected = true;
                        }
                        if (!proj.isCompleted) {
                            isCompleted = false;
                            break;
                        }
                        
                        var checkedItems = ["isBindErp","authorizeUseStatus","isParamsSyncErp","isCreateSalesTeam"];
                        var done = true;
                        for(var j = 0; j < checkedItems.length; j++) {
                            if (checkedItems[j] === "authorizeUseStatus") {
                                if (!proj[checkedItems[j]].used || !proj[checkedItems[j]].used.length) {
                                    done = false;
                                    break;
                                }
                            } else if (checkedItems[j] === "isParamsSyncErp" && proj[checkedItems[j]] == false && !proj.authYDXS) {
                                
                            } else if (proj[checkedItems[j]] == false) {
                                done = false;
                                break;
                            }
                        }
                        
                        if (proj.authYDXS) {
                            unAuthYDXS = false;
                        }
                        if (!done) {
                            isCompleted = false;
                            break;
                        }
                        $scope.selectedProjList[i].checkedOk = true;
                    } 
                    if (isCompleted  || $scope.isDebug) {
                        $scope.checkedProjOk = true;
                        $scope.unAuthYDXS = unAuthYDXS;
                    }
                    
                };
                
                $scope.getBindErpUrl = function(proj){
                    return "/page/houses_manage/house_manage.shtml?projId=" + proj.id + "#/project_info";
                };
                
                $scope.getAuthorizeUrl = function(proj){
                    return "/page/houses_manage/house_manage.shtml?projId=" + proj.id + "#/project_role";
                };
                
                $scope.getCreateTeamUrl = function(proj) {
                    return "/page/user_manage/salesteam_manage.html?projId=" + proj.id;
                };
                /** 
                 * 绑定erp 
                 */
                $scope.erpBinder = {
                    init: function(scope,proj) {
                        service.getUnbindErpUsers({
                            search: {
                                projectId: proj.id
                            }
                        })  
                            .then(function(res){
                                scope.users = res.data;
                            })  
               
                    },
                    ok: function(proj){
                        util.download(service.exportUnbindErpUsers({
                            search: {
                                projectId: proj.id
                            }
                        }));
                    }
                }
                
                /** 
                 * 同步erp业务 
                 */
                $scope.erpSync = {
                    init: function(scope,proj) {
                        scope.getSyncErpList = function(){         
                            service.getSyncErpList({
                                search: {
                                    proj_id: proj.id,
                                    app_code: "5002"
                                }
                            })
                                .then(function(res){
                                    scope.busis = res.data.info;
                                })
                        };
                            
                        
                        scope.sync = function(busi){
                            service.syncErpParam({
                                data: {
                                    proj_id: proj.id,
                                    sync_param_id: busi.s_param2ERPparamId
                                }
                            })
                                .then(function(res){
                                    scope.getSyncErpList();
                                })
                        };
                        
                        scope.updateBusi = function(data,$dialog,index) {
                            service.updateErpParam({
                                data: {
                                    customParams: [angular.extend(data,{
                                        Applications: data.Application
                                    })],
                                    proj_id: proj.id
                                }
                            })
                                .then(function(res){
                                    scope.getSyncErpList();
                                })
                        };
                        
                        scope.syncMulti = function(){
                            
                            service.syncErpParams({
                                data: {
                                    proj_id: proj.id
                                }
                            })
                                .then(function(res){
                                    scope.getSyncErpList();
                                })
                        };
                        
                        scope.importErp = function(model){
                            service.importSyncErpList({
                                search: {
                                    proj_id: proj.id,
                                    param_model: model
                                }
                            })
                                .then(function(res){
                                    scope.getSyncErpList();
                                })
                        };
                        
                        scope.getSyncErpList();
                    },
                    save: function(scope,proj,dialog){                        
                        
                    }
                };
                
                
                /** 
                 * 显示规则选择界面
                 */
                $scope.showRules = function () {
                    if (!$scope.checkedProjOk || !$scope.isSiteOk){
                        return;
                    }
                    $scope.curStep = "selectRule";
                };
                
                $scope.customerTypes = [
                    {value: '6', text: '最近6个月有跟进'},
                    {value: '3', text: '最近3个月有跟进'},
                    {value: '2', text: '最近2个月有跟进'},
                    {value: '1', text: '最近1个月有跟进'},
                    {value: '0', text: '所有'}
                ];
                
                $scope.customer = $scope.customerTypes[0].value;
                
                $scope.protectDateTypes = [
                    {value: 'today', text: '今天'},
                    {value: 'lastgj', text: '最后一次跟进日期'}
                ];
                
                $scope.protectDate = $scope.protectDateTypes[0].value;
                
                $scope.saveInitRules = function(){
                    $scope.getUserInitData(function(res){
                        if (res.data || $scope.isDebug) {
                            var projectIds = [];
                            angular.forEach($scope.selectedProjList,function(proj){
                                projectIds.push(proj.id);
                            });
                            service.saveInitRules({
                                data: angular.extend({
                                    projectIds: projectIds
                                },$scope.customer ? {
                                    start: $scope.customer,
                                    end: $scope.protectDate
                                } : {})
                            })
                                .then(function(res){
                                    $scope.syncProj();
                                })
                        } else {
                            $rootScope.$emit('httpRequestError',"当前存在初始化的项目")
                        }
                    })
                    
                };
                
               
                /** 
                 * 同步项目
                 */
                $scope.syncProj = function () {
                    $scope.curStep = "syncProj";
                    
                    $scope.interval = setInterval(function(){
                        $scope.$apply(function(){
                            $scope.getUploadStatus();
                        });
                    },1000);
                };

                /** 
                 * 获取步骤信息
                 */
                $scope.getUploadStatus = function(){
                    service.getStepStatus({
                        search: {}
                    })
                        .then(function(res){
                            $scope.stepStatus = res.data;
                            $scope.checkUploadStatus();
                        })

                };
                
                $scope.checkUploadStatus = function(){
                    var isStatusOk = true;
                    for (var i = 0; i < $scope.stepStatus.length; i++) {
                        var step = $scope.stepStatus[i];
                        if (step.error_info) {
                            isStatusOk = false;
                            clearInterval($scope.interval); 
                            $rootScope.$emit('httpRequestFail',"初始化失败，" + step.error_info);
                            break;
                        }
                        if (step.total !== step.current) {
                            isStatusOk = false;
                            break;
                        }
                    }
                    if (isStatusOk || $scope.isDebug){
                        clearInterval($scope.interval);   
                        $scope.getInitStatus();
                        $scope.interval = setInterval(function(){
                            $scope.$apply(function(){
                                $scope.getInitStatus();
                            });
                        },1000);           
                    }
                };
                
                $scope.checkInitStatus = function(){
                    var isStatusOk = true;
                    var initCount = 0;
                    for (var i = 0; i < $scope.statusList.length; i++) {
                        var step = $scope.statusList[i];
                        if (step.error_info) {
                            isStatusOk = false;
                            clearInterval($scope.interval); 
                            $rootScope.$emit('httpRequestFail',"初始化失败，" + step.error_info);
                            break;
                        }
                        if ((step.total == step.current && step.total !== -1) || step.total == 0) {
                            initCount++;
                        } else {
                            isStatusOk = false;
                            break;
                        }
                    }
                    $scope.initCount = initCount;
                    if (isStatusOk || $scope.isDebug){
                        clearInterval($scope.interval);  
                        $scope.initCompleted = true; 
                    }
                };
                /**
                 * 获取初始化状态
                 */
                $scope.getInitStatus = function () {
                    service.getInitStatus({
                        search: {}
                    })
                        .then(function (res) {
                            $scope.uploaded = true;
                            if ($scope.isDebug) {
                                res.data = res.data.map(function(info) {
                                    return angular.extend(info,{
                                        conflict_count: 1,
                                        not_in_sale_team_count: 22
                                    })
                                })
                            }
                            $scope.statusList = res.data;
                            $scope.checkInitStatus();
                        })
                };
                
                /** 
                 * 销售员相关
                 */
                $scope.salerAdder = {
                    init: function (scope,proj) {
                        var projs = [];
                        angular.forEach($scope.statusList,function(proj){
                            projs.push(proj.projectId);
                        });
                        scope.curProjectId = proj.projectId;
                        service.getSalerProjectList({
                            data: {
                                flag: 0,
                                jointparent: 1,
                                'projectids': projs.join(',')
                            }
                        })
                            .then(function (res) {
                                var data = res.data
                                
                                scope.projectList = data;
                            });
                            
                        
                        /** 
                         * 分页组件
                         */
                        scope.pager = {
                            pageIndex: 1,
                            pageSize: 10,
                            change: function(pageIndex){
                                scope.searchSalerList({
                                    page_index: pageIndex
                                });
                            }
                        };
                        /** 
                         * checkbox组件
                         */
                
                        scope.checker = {
                            all: false,
                            checkAll: function () {
                                var selected = false;
                                for (var i = 0; i < scope.users.length; i++) {
                                    if (scope.users[i] && scope.users[i].isdisabled == 0) {
                                        scope.users[i].checked = scope.checker.all;
                                        selected = true;
                                    }
                                }
                                
                                if (scope.users.length){
                                    scope.checker.selected = selected && scope.checker.all;                                    
                                }
                            },
                            check: function (select,index) {
                                var all = true;
                                scope.checker.selected = false;
        
                                for (var i = 0; i < scope.users.length; i++) {
                                    var user = scope.users[i];
                                    
                                    if (user.checked) {
                                        scope.checker.selected = true;
                                    } else {
                                        all = false;
                                    }
                                    if (select.isdisabled == 1 && index === i) {
                                        user.checked = false;
                                        all = false;
                                        $rootScope.$emit('httpRequestError',"离职成员不能加入团队")
                                    }
                                }
        
                                scope.checker.all = all;
                            }

                        };
                        
                        scope.getTeamInfo = function() {
                            service.getTeamInfo({
                                search: {
                                    proj_id: scope.curProjectId
                                }
                            })
                                .then(function(res){
                                    scope.teamInfo = res.data;
                                })
                        };
                        
                        /** 
                         * 搜索
                         */
                        scope.search = function() {
                            scope.searchSalerList({
                                page_index: 1
                            });
                        };
                        
                        /** 
                         * 加入团队
                         */
                        scope.addTeamUser = function(users,role,team){
                            var userIds = [];
                            if (angular.isArray(users)) {
                                angular.forEach(users,function(user){
                                    if (user.checked){
                                        userIds.push(user.team_user_id);                                        
                                    }
                                })
                            } else {
                                userIds.push(users.team_user_id);
                            }
                            
                            var data = {
                                team_user_id: userIds.join(','),
                                user_type: role
                            };
                            
                            team = team || {};
                            if (team.team_id) {
                                data.target_team_id = team.team_id;
                            }
                            if (team.group_id) {
                                data.target_group_id = team.group_id;
                            }
                            return service.addTeamUsers({
                                data: data
                            }).then(function(res){
                                    scope.searchSalerList({
                                        page_index: 1
                                    });
                                })
                        };
                        
                        /** 
                         * 置为离职
                         */
                        scope.markDeparture = function(user){
                            service.markDeparture({
                                data: {
                                    s_userId: user.user_id
                                }
                            })
                                .then(function(res){
                                    scope.searchSalerList()
                                        .then(function(){
                                            $rootScope.$emit('httpRequestSuccess',"置为离职成功")
                                        });
                                })
                        };
                        /** 
                         * 置为在职
                         */
                        scope.markOnDuty = function(user){
                            service.markOnDuty({
                                data: {
                                    s_userId: user.user_id
                                }
                            })
                                .then(function(res){
                                    scope.searchSalerList()
                                        .then(function(){
                                            $rootScope.$emit('httpRequestSuccess',"置为在职成功")
                                        });
                                })
                        };
                        /**
                         * 完善资料
                         */
                        scope.updateSaler = function(data,dialog){
                            if (!data.user_name) {
                                $rootScope.$emit('httpRequestError',"姓名不能为空");
                                return false;
                            }
                            
                            if (!data.mobile_tel) {
                                $rootScope.$emit('httpRequestError',"手机号不能为空");
                                return false;
                            }
                            
                            if (!/^\d{11}$/.test(data.mobile_tel)){
                                $rootScope.$emit('httpRequestError',"手机号格式不正确");
                                return false;
                            }
                            service.updateSaler({
                                data: {
                                    s_userId: data.user_id,
                                    user_name: data.user_name,
                                    mobile_tel: data.mobile_tel
                                }
                            })
                                .then(function(res){
                                    scope.searchSalerList();
                                    dialog.close();
                                })
                        };
                        scope.searchSalerList = function(opts){
                            scope.keyword = scope.search_text;
                            opts = opts || {
                                page_index: scope.pager.pageIndex
                            };
                            return service.getSalerList({
                                search: angular.extend(opts,{
                                    page_size: scope.pager.pageSize,
                                    proj_id: scope.curProjectId,
                                    keyword: scope.keyword || ""
                                })
                            })
                                .then(function(res){
                                    scope.pager.total = res.data.total;
                                    scope.pager.pageIndex = opts.page_index;
                                    var data = res.data.items;
                                    
                                    angular.forEach(data,function(user,index){
                                        if (!/^\d{11}$/.test(user.mobile_tel) || !user.user_name) {
                                            user.imcompleted = true;
                                        }
                                    });
                                    scope.users = data;
                                })
                        };
                        
                    
                        
                        scope.$watch('curProjectId',function(projId){
                            if (projId){
                                scope.searchSalerList();
                                scope.getTeamInfo();
                            }
                        });
                        
                       
                    }
                };
                
                $scope.complete = function(){
                    if (!$scope.initCompleted){
                        return;
                    }
                    clearInterval($scope.interval);  
                    $scope.cancelInitCheck();
                    $scope.refresh();
                };
                
                $scope.getUserInitData = function(cb){
                    service.getUserInitData({
                        search: {}
                    })
                        .then(function(res){
                            cb && cb(res);
                        })
                }
                
                $scope.refresh = function(){
                    $scope.getUserInitData(function(res){
                        if (res.data || $scope.isDebug) {
                            $scope.getProjectList();
                        } else {
                            $scope.syncProj();
                        }
                    })
                }
                /** 
                 * 初始化
                 */
                $scope.refresh();
                        
                $scope.isDebug = false;
                
                $window.onbeforeunload = function(){
                    if ($scope.curStep != "selectProj") {
                        return "所选项目尚未初始化完成";
                    }
                }
            }
        ])

    
    angular.element(document).ready(function () {
        angular.bootstrap(document, ['app']);
    }); 
});